#include <stdio.h>
#include <string.h>
#include <iconv.h>
#define OUTLEN 255

int code_convert(char *from_charset, char *to_charset, char *inbuf, int inlen, char *outbuf, int outlen)
{
    iconv_t cd;
    int rc;
    char **pin = & inbuf;
    char **pout = &outbuf;

    cd = iconv_open(to_charset, from_charset);
    if(cd == 0) return -1;
    memset(outbuf, 0, outlen);
    if(iconv(cd, pin, &inlen, pout, &outlen) == -1) return -1;
    iconv_close(cd);

    return 0;
}

/* from UNICODE to GB2312 */
int u2g(char *inbuf, int inlen, char *outbuf, int outlen)
{
    return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
}

int g2u(char *inbuf, int inlen, char *outbuf, int outlen)
{
    return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);
}

int main(int argc, char *argv[])
{
    char *in_utf8 = "姝ｅ?ㄥ??瑁?";
    char *in_gb2312 = "正在安装";
    char out[OUTLEN];
    char str[OUTLEN] = "一万";

    printf("chinese %s\n", str);
    printf("in_gb2312=%s, len = %d\n", in_gb2312, strlen(in_gb2312));
    printf("in_utf8=%s, len = %d\n", in_utf8, strlen(in_utf8));
    u2g(in_utf8, strlen(in_utf8), out, OUTLEN);
    printf("unicode-->gb2312 out=%s\n", out);

    g2u(in_gb2312, strlen(in_gb2312), out, OUTLEN);
    printf("gb2312-->unicode out=%s\n", out);

    return 0;
}
